var http = require('http'),
    sys = require('sys');

var server = http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(8081, 'localhost');

server.on('upgrade', function (request, socket, head) {
    console.log('head:', head.toString('utf8'));

    socket.write( "HTTP/1.1 101 Web Socket Protocol Handshake\r\n"
        + "Upgrade: WebSocket\r\n"
        + "Connection: Upgrade\r\n"
        + "WebSocket-Origin: http://localhost:8081\r\n"
        + "WebSocket-Location: ws://localhost:8081/\r\n"
        + "\r\n"
    );

    socket.ondata = function(d, start, end){
//        var data = d.toString('utf8', start, end);
        var original_data = d.toString('utf8', start, end);
        var data = original_data.split('\ufffd')[0].slice(1);
        var match = data.match(/^((:?\\?[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)+)::([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\((.*)\)$/)

        socket.write("\u0000", "binary");
        socket.write(JSON.stringify({
            'class'  : match[1],
            'method' : match[3],
            'args'   : JSON.parse('[' + match[4] + ']')
        }), "utf8");
        socket.write("\uffff", "binary");
    };

});